package psn.james.kaixin.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jdom.Document;
import org.jdom.input.SAXBuilder;

import psn.james.kaixin.KaiXinFarm;

public class Network {
	public static final String KAIXINNETWORK = "http://www.kaixin001.com";
	
	private static InputStream callURL(String urlStr, String cookies){
		URLConnection connection;
		try {
			URL url = new URL(urlStr);
			connection = url.openConnection();
			connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316");
			connection.setRequestProperty("Keep-Alive", "300");
			connection.setRequestProperty("Connection", "keep-alive");
			connection.setRequestProperty("Cookie", cookies);
			return connection.getInputStream();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			updateCookies();
		}
		return null;
	}
	
	public static String getStringResponse(String url, String cookies){
		StringBuffer htmlBuffer = new StringBuffer();
		InputStream is = callURL(url, cookies);
		BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
		
		try {
			String data;
			while((data = br.readLine()) != null)
				htmlBuffer.append(data);
		} catch (IOException e) {
			updateCookies();
		}
		return htmlBuffer.toString();
	}
	
	public static Document getXMLResponse(String url, String cookies){
		try {
			return new SAXBuilder().build(callURL(url, cookies));
		} catch (Exception e) {
			updateCookies();
		}
		return null;
	}
	
	private static void updateCookies(){
		KaiXinFarm.COOKIES = Network.getCookies(KaiXinFarm.USERNAME, KaiXinFarm.PASSWORD);
		KaiXinFarm.VERIFYCODE = Network.getVerifyCode(KaiXinFarm.COOKIES);
	}
	
	public static String getCookies(String userName, String password){
		StringBuffer cookiesBuffer = new StringBuffer();
		try {
			String urlStr = KAIXINNETWORK + "/login/login.php";
			String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
				+ "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316");
			conn.setRequestProperty("Keep-Alive", "300");
			conn.setRequestProperty("Connection", "keep-alive");
			conn.setDoOutput(true);
			conn.setInstanceFollowRedirects(false);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();
			wr.close();
			
			List<String> cookiesStrList = conn.getHeaderFields().get("Set-Cookie");
			for (String cookiesStr : cookiesStrList)
				cookiesBuffer.append(cookiesStr + ";");			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return cookiesBuffer.toString();
	}
	
	public static String getVerifyCode(String cookies){
		String respStr = getStringResponse(KAIXINNETWORK + "/!house/garden/index.php", cookies);
		String regex = "g_verify\\s*=\\s*\"([^\"]*)\"";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(respStr);
		if(m.find())
			return m.group(1);		
		return "";
	}
	
	public static String getUID(String cookies) {
		String regex = "_uid\\s*=\\s*(\\d*);";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(cookies);
		if(m.find())
			return m.group(1);
		return "";
	}
}